package com.symbio.ishenapi.prescription.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.symbio.ishenapi.common.controller.BaseController;
import com.symbio.ishenapi.prescription.model.TmPrescriptionAttr;
import com.symbio.ishenapi.prescription.model.TmPrescriptionMain;

import com.symbio.ishenapi.prescription.model.TmPrescriptionOrder;
import com.symbio.ishenapi.prescription.model.TmPrescriptionParcel;
import io.jboot.web.controller.annotation.RequestMapping;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("/TmPrescriptionMainl")
public class TmPrescriptionController extends BaseController {

    public void findTmhospitalDepartment(){
        TmPrescriptionMain tm = (TmPrescriptionMain) getReqBodyObject(TmPrescriptionMain.class);
        if (TmPrescriptionMain.dao.findById(tm.getId()) !=null){
            renderJsonError(40001);
            return;
        }
        if (tm.save()){
            renderJsonRet(tm);
        }else {
            renderJsonError(40002);
        }
    }


    /**
     *
     *
     * @Author GuoShunYou
     * @Description 根据处方id查询处方详情
     * @date 下午 2:22   2018/10/22 0022
     * @return void
     */
    public void find(){
        TmPrescriptionMain tmpres = (TmPrescriptionMain) getReqBodyObject(TmPrescriptionMain.class);
        List<TmPrescriptionMain> order = TmPrescriptionMain.dao.findTmPrescriptionMain(tmpres);
        renderJsonRet(order);
    }

    /*public void findall(){
        TmPrescriptionAttr tmpres = (TmPrescriptionAttr) getReqBodyObject(TmPrescriptionAttr.class);
        renderJsonRet(TmPrescriptionAttr.dao.findTmPrescriptionAttr(tmpres));
    }*/

    /**
     * wy:开诊断
     */
    public void saveDiagnose(){
        TmPrescriptionMain tm = (TmPrescriptionMain) getReqBodyObject(TmPrescriptionMain.class);
        if (tm.getOrderId() != null && tm.getUserId()!= null && tm.getDoctorId() != null){
            try{
                tm.setRunWater(getWaterNum());
                tm.setCreateTime(new Date());
                if (tm.save()){
                    renderJsonRet(tm);
                }else {
                    renderJsonError(50002,"添加");
                    return;
                }
            }catch (Exception e){
                renderJsonError(50002,"添加");
                e.printStackTrace();
            }
        }else {
            renderJsonError(40003,"信息");
        }
    }

    /**
     * 生成流水号接口
     * @return
     */
    public static String getWaterNum() {
        Date currentDate = new Date();
        SimpleDateFormat date = new SimpleDateFormat("yyMMdd");
        long s = currentDate.getTime();
        String time = String.valueOf(s);
        String substring = time.substring(time.length() - 4);

        String string = date.format(currentDate) + substring;
        return string;
    }

    /**
     * wy:修改诊断
     */
    public void updateDiagnose(){
        TmPrescriptionMain tm = (TmPrescriptionMain) getReqBodyObject(TmPrescriptionMain.class);
        try {
            if (tm.update()){
                renderJsonRet(50001);
            }else {
                renderJsonError(50002,"修改");
                return;
            }
        }catch (Exception e){
            renderJsonError(50002,"修改");
            e.printStackTrace();
        }
    }

    /**
     * wy:开处方
     */
    public void savePrescription(){
        List<TmPrescriptionAttr> tp  = new ArrayList<>();
        String json = getReqBodyString();
        int count = 0;

        tp = JSON.parseArray(json, TmPrescriptionAttr.class);
        for (TmPrescriptionAttr attr : tp){
            attr.setCreateTime(new Date());
            attr.setTotalPrice(attr.getSalePrice()*attr.getNumber());
            if (attr.save()){
                count +=1;
            }else {
                renderError(50002,"保存处方");
                return;
            }
        }
        if (count == tp.size()){
            renderJsonRet(50001);
        }else {
            renderJsonError(50002,"保存处方");
            return;
        }
    }

    /**
     * wy:修改处方
     */
    public void updatePrescription(){
        TmPrescriptionAttr tp = (TmPrescriptionAttr) getReqBodyObject(TmPrescriptionAttr.class);
        if (tp.getId() != null && !"".equals(tp.getId())){
            tp.setCreateTime(new Date());
            tp.setTotalPrice(tp.getSalePrice()*tp.getNumber());
            try {
                if (tp.update()){
                    renderJsonRet(tp);
                }else {
                    renderJsonError(50002,"修改");
                    return;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            renderJsonError(50002,"修改");
            return;
        }
    }

    /**
     * wy:删除处方
     */
    public void delPrescription(){
        TmPrescriptionAttr tp = (TmPrescriptionAttr) getReqBodyObject(TmPrescriptionAttr.class);
        try {
            if (tp.deleteById(tp.getId())){
                renderJsonRet(50001);
            }else {
                renderJsonError(50002,"删除");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * wy:查询医生处方是否购买
     *  wy:根据订单id  orderId
     *  查询处方药品表
     */
    public void findIsPurchasedPre(){
        String purchased = getPara("purchased");
        String orderId = getPara("orderId");
        TmPrescriptionAttr tp = new TmPrescriptionAttr();
        try {
            if (orderId != null && !"".equals(orderId)){
                Map map = tp.findisPurchasedPre(getQueryModel(),purchased,orderId);
                renderPageJsonRet(map.get("count"),map.get("data"));
            }else {
                renderJsonError(50002,"查询");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * wy:根据订单ID
     * 查询处方诊断表
     */
    public void findMain(){
        TmPrescriptionMain tp = (TmPrescriptionMain) getReqBodyObject(TmPrescriptionMain.class);
        try {
            if (tp.getOrderId() != null && !"".equals(tp.getOrderId())){
                TmPrescriptionMain map  = tp.findMainAndPre(tp);
                renderJsonRet(map);
            }else {
                renderJsonError(50002,"查询");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * wy:保存处方订单
     *    未支付状态
     */
    public void savePreOrder(){
        TmPrescriptionOrder tpo = (TmPrescriptionOrder) getReqBodyObject(TmPrescriptionOrder.class);
        TmPrescriptionAttr tpa = new TmPrescriptionAttr();
        try {
            if (tpo.getDoctorId() != null && !"".equals(tpo.getDoctorId()) && tpo.getUserId() != null && !"".equals(tpo.getUserId()) && tpo.getMainId() != null && !"".equals(tpo.getMainId()) && tpo.getOrderId() != null && !"".equals(tpo.getOrderId()) && tpo.getCarryMoney() != null && !"".equals(tpo.getCarryMoney())){
                Double totalMoney = 0.00;
                String drugIds = tpo.getDrugIds();

                //
                if(drugIds == null && "".equals(drugIds)){
                    renderJsonError(50002,"提交订单");
                    return;
                }
                List<TmPrescriptionAttr> byGroup = tpa.findByGroup(drugIds);
                tpo.setCreateTime(new Date());
                for (int i = 0; i <byGroup.size(); i++){
                    TmPrescriptionParcel tpp = new TmPrescriptionParcel();
                    String storage = byGroup.get(i).getStorage();
                    tpp.setStorage(storage); //设置发货商
                    tpp.setRunWater(tpo.getRunWater()); //设置流水号
                    tpp.setConsignee(tpo.getConsignee());
                    tpp.setConsigneeTEL(tpo.getConsigneeTEL());
                    tpp.setConsigneeCity(tpo.getConsigneeCity());
                    tpp.setUserId(tpo.getUserId());
                    tpp.setDoctorId(tpo.getDoctorId());
                    tpp.setMainId(tpo.getMainId());
                    tpp.setCreateTime(tpo.getCreateTime());
                    tpp.setPaymentStatus(tpo.getPaymentStatus());
                    tpp.setOrderId(tpo.getOrderId());
                    tpp.setCarryMoney(tpo.getCarryMoney());
                    tpp.setActualMoney(tpo.getActualMoney());
                    String tppids = new String();
                    BigInteger id = null;
                    Double totalPrice = null;
                    List<TmPrescriptionAttr> byStorage = tpa.findByStorage(storage,drugIds);
                    for (int j = 0; j <byStorage.size(); j++){
                        id = byStorage.get(j).getId();
                        totalPrice = byStorage.get(j).getTotalPrice();
                        tppids += (id.toString());
                        totalMoney += totalPrice;
                    }

                    //保存到包裹表
                    tpp.setDrugIds(tppids);
                    tpp.setIsDelivery("0");
                    tpp.setDrugMoney(totalMoney);
                    tpp.setTotalMoney(totalMoney + tpp.getCarryMoney());
                    tpp.save();
                }
                tpo.setPaymentStatus("0");
                tpo.setDrugMoney(totalMoney);
                tpo.setTotalMoney(totalMoney + tpo.getCarryMoney());
                tpo.save();
                renderJsonRet(tpo);
                return;

            }else {
                renderJsonError(50002,"提交订单");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * wy:支付成功后修改处方订单
     *    支付状态(支付成功:"1")
     */
    public void updatePreOrder(){
        TmPrescriptionOrder t = (TmPrescriptionOrder) getReqBodyObject(TmPrescriptionOrder.class);
        TmPrescriptionAttr tpa = new TmPrescriptionAttr();
        try {
            TmPrescriptionOrder tpo = t.findById(t.getId());
            if (tpo.getOrderId() != null && !"".equals(tpo.getOrderId())){
                tpo.setPaymentStatus("1");//修改处方订单表订单状态
                if (tpo.update()){
                    //修改处方药品表是否购买状态
                    String drugIds = t.getDrugIds();
                    String[] split = drugIds.split(",");
                    for (int a = 0; a <split.length; a++){
                        tpa.updateIds(split[a],tpo.getOrderId());
                    }
                    //修改处方物流包裹表状态
                    TmPrescriptionParcel tppar = new TmPrescriptionParcel();
                    List<TmPrescriptionParcel> lists = tppar.findByRunWater(tpo.getOrderId());
                    for (TmPrescriptionParcel tpp : lists){
                        tpp.setPaymentStatus(tpo.getPaymentStatus());
                        tpp.update();
                    }
                    renderJsonRet(tpo);
                }
            }else {
                renderJsonError(50002,"修改");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * wy:支付成功后显示
     *
     */
    public void findByIds(){
        TmPrescriptionOrder tpo = (TmPrescriptionOrder) getReqBodyObject(TmPrescriptionOrder.class);
        TmPrescriptionParcel tpp = new TmPrescriptionParcel();
        TmPrescriptionAttr tpa = new TmPrescriptionAttr();
        Map map = new HashMap();
        BigInteger orderId = tpo.getOrderId();
        try {
            if (tpo.getOrderId() != null && !"".equals(tpo.getOrderId())){
                TmPrescriptionOrder order = tpo.findByRunWater(orderId);
                map.put("order",order);
                List<TmPrescriptionParcel> parcels = tpp.findByRunWater(orderId);
                map.put("parcels",parcels);
                List<TmPrescriptionAttr> attrs = tpa.findByRunWater(orderId);
                map.put("attrs",attrs);
                renderJsonRet(map);
            }else {
                renderJsonError(50002,"查询");
                return;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * wy:根据订单ID查询病历信息
     */
    public void findAttrIdAndPreMain(){
        TmPrescriptionMain tpm = (TmPrescriptionMain)getReqBodyObject(TmPrescriptionMain.class);
        if(tpm.getOrderId() != null && !"".equals(tpm.getOrderId())){
            TmPrescriptionMain main = tpm.findAttrIdAndPreMain(tpm);
            renderJsonRet(main);
        }else {
            renderJsonError(40003);
        }
    }

    /**
     * 根据订单ID获取物流费
     */
    public void findCarrymoney(){
        String id = getPara("orderId");
        TmPrescriptionParcel tpp = new TmPrescriptionParcel();
        BigInteger orderId = new BigInteger(id);
        renderJsonRet(tpp.findCarrymoney(orderId));
    }

    /**
     * wy:根据患者ID,医生ID获取原诊断
     */
    public void findByIdToRawDiagnose(){
        TmPrescriptionMain tpm = (TmPrescriptionMain)getReqBodyObject(TmPrescriptionMain.class);
        TmPrescriptionMain main = tpm.findByIdToRawDiagnose(tpm);
        if (main != null && !"".equals(main.getDiagnose()) && main.getDiagnose() != null){
            renderJsonRet(main.getDiagnose());
            return;
        }else {
            renderJsonError(40003,"查询");
            return;
        }
    }
}